<?php

namespace App\Jobs;

use App\Store\Models\Goods\GoodsStockin;
use App\Store\Models\Goods\GoodsStockinInfolist;
use App\Store\Models\Goods\GoodsStockList;
use App\Store\Services\Goods\Goods;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockinAuditJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    /**
     * 入库审核
     */
    const QUEUE_JOB = 'stockin-audit-job';
    public $tries = 3;

    public $initdata = [];

    public $accountinfo = [];
    public $jobId = '';



    public function __construct($data, $accountinfo)
    {
        set_time_limit(0);
        $this->initdata = $data;
        $this->accountinfo = $accountinfo;
        $this->onQueue(self::QUEUE_JOB);

    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {

        $this->jobId = $this->job->getJobId();


        Log::info('任务ID'.$this->jobId);

        set_time_limit(-1);
        ini_set('memory_limit', -1);

        $data = $this->initdata;
        $cp_id = $this->accountinfo['cp_id'] ?? 0;

        Log::info('审核数据',$data);
        Log::info('账号信息',$this->accountinfo);
        if (empty($data)) {
            Log::info('暂无数据');
        }
        DB::beginTransaction();
        try {
            foreach ($data as $info) {
                //增加逻辑 入库存列表，保证条码唯一
                $isexist = GoodsStockList::where(['cp_id' => $cp_id, 'goods_sn_code' => $info['goods_sn_code'], 'is_del' => 1])->first();
                if ($isexist) {
                    Log::info('条码：' . $info['goods_sn_code'] . '已存在');
                } else {
                    $id = $info['id'];
                    GoodsStockinInfolist::where(['id' => $id, 'cp_id' => $cp_id, 'store_id' => $info['store_id']])->update(['audit_status' => 2, 'audit_success_count' => $info['count'], 'audit_at' => time()]);
                    //入库操作
                    $data = $info;
                    unset($data['id']);
                    unset($data['p_id']);
                    unset($data['audit_status']);
                    unset($data['audit_at']);
                    $data['create_at'] = time();
                    $data['start_stockin_store_id'] = $data['store_id'];
                    $data['piece_weight'] = $data['piece_weight_new'];
                    $data['netglod_weight'] = $data['netglod_weight_new'];
                    $data['label_price'] = $data['label_price_new'];
                    $data['total_piece_weight'] = $data['total_piece_weight_new'];
                    $data['total_netglod_weight'] = $data['total_netglod_weight_new'];

                    GoodsStockList::query()->create($data);
                    $audit_status_count = GoodsStockinInfolist::where(['p_id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $info['store_id'], 'audit_status' => 1])->count();
                    if ($audit_status_count > 0) {
                        $audit_status = 2;
                    } else {
                        $audit_status = 3;
                    }
                    GoodsStockin::where(['id' => $info['p_id'], 'cp_id' => $cp_id, 'store_id' => $info['store_id']])->increment('audit_success_count', $info['count'], ['audit_status' => $audit_status, 'audit_at' => time()]);
                    (new Goods())->addGoodLogs($this->accountinfo, 0, intval($info['store_id']), $info, intval($info['count']), 1, $info['order_sncode']);
                }
            }

            DB::commit();

        } catch (\Exception $e) {
            Log::info('商品入库审核失败' . $e->getLine() . $e->getMessage());
            $this->handleFailure($e);
            DB::rollBack();
        }
    }


    protected function handleFailure(\Throwable $e)
    {
        // 参数错误立即失败，不重试
        if ($e instanceof \InvalidArgumentException) {
            $this->failed($e);
            return;
        }

        // 可重试错误：达到最大尝试次数后标记失败
        if ($e instanceof \RuntimeException) {
            if ($this->attempts() >= $this->tries) {
                $this->failed($e);
            } else {
                throw $e;
            }
        }
    }

    public function failed(\Throwable $exception)
    {
        Log::info($exception->getMessage());
    }
}
